import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent, STData } from '@delon/abc/st';
import { SFDateWidgetSchema, SFSelectWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { TaxManagementService } from '../../services/tax-management.service';

@Component({
  selector: 'app-tax-management-invoice-reporting',
  templateUrl: './invoice-reporting.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class TaxManagementInvoiceReportingComponent extends BasicTableComponent implements OnInit {
  columns!: STColumn[];
  tabType!: string;
  isLoading: boolean = false;
  tabs: any[] = [
    { name: '待上传', value: '1' },
    { name: '上传中', value: '2' },
    { name: '已上传', value: '3' },
    { name: '异常', value: '4' },
    { name: '全部', value: '' }
  ];
  selectedIndex = '1'; //选择的项目
  serviceTel = '';
  constructor(public service: TaxManagementService, private modal: NzModalService, public searchDrawerService: SearchDrawerService) {
    super(searchDrawerService);
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {}, { uploadSts: this.selectedIndex });
    delete params._$expand;
    return { ...params };
  }

  /**
   * 选中行
   */
  get selectedRows() {
    return this.st?.list.filter((item: any) => item.checked) || [];
  }

  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.initSF();
    this.initST();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        // uploadSts: {
        //   title: '上传状态',
        //   type: 'string',
        //   default: '1',
        //   enum: [
        //     { label: '全部', value: '' },
        //     { label: '待上传', value: '1'},
        //     { label: '上传中', value: '2' },
        //     { label: '已上传', value: '3' },
        //     { label: '异常', value: '4' }
        //   ],

        //   ui: {
        //     placeholder: '请选择',
        //     widget: 'select',
        //     allowClear: true
        //   }
        // },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          }
        },
        arto: {
          type: 'string',
          title: '购买方',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getCRMCustomerId()
          }
        },
        billHCode: {
          title: '订单号',
          type: 'string',
          ui: {
            placeholder: '请输入'
          }
        },
        invoicedate: {
          title: '开票日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        uoloadDate: {
          title: '上传日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        invoiceno: {
          type: 'string',
          title: '发票号码',
          ui: {
            placeholder: '请输入'
          }
        },
        invoiceno2: {
          type: 'string',
          title: '发票代码',
          ui: {
            placeholder: '请输入'
          }
        },
        sts: {
          title: '发票状态',
          type: 'string',
          ui: {
            widget: 'dict-select',
            containsAllLabel: true,
            params: { dictKey: 'vatinv:status' },
            containAllLable: true
          } as SFSelectWidgetSchema
        }
      }
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', className: 'text-center', width: '60px' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      { title: '上传状态', render: 'uploadSts', className: 'text-center', width: '120px' },
      { title: '发票类型', render: 'invoiceType', className: 'text-center', width: '180px' },
      {
        title: '发票号码',
        index: 'invoiceno',
        className: 'text-center',
        width: '120px',
        type: 'link',
        click: item => {
          window.open(`/#/ticket/invoice-list/detail/${item.vatinvHId}?type=${item.invoiceType}`, '_blank', 'noopener');
        }
      },
      { title: '发票代码', index: 'invoiceno2', className: 'text-center', width: '150px' },
      {
        title: '网络货运人',
        index: 'ltdName',
        className: 'text-center',
        width: '180px'
      },
      {
        title: '购买方企业名称',
        index: 'artoname',
        className: 'text-center',
        width: '200px',
        type: 'link',
        click: item => {
          window.open(`/#/usercenter/freight/list/detail/${item.arto}`, '_blank', 'noopener');
        }
      },
      { title: '购买方统一社会信用代码', index: 'artotaxno', className: 'text-center', width: '200px' },
      {
        title: '订单号',
        index: 'billHCode',
        className: 'text-center',
        width: '180px',
        type: 'link',
        click: item => {
          window.open(`/#/order-management/vehicle/vehicle-detail/${item.ltdId}`, '_blank', 'noopener');
        }
      },
      { title: '货物名称', index: 'goodsinfo', className: 'text-center', width: '120px' },
      { title: '价税合计', index: 'vatmoney', className: 'text-center', width: '120px' },
      { title: '开票日期', index: 'invoicedate', className: 'text-center', width: '180px' },
      { title: '发票所属月份', index: 'invoicemonth', className: 'text-center', width: '140px' },
      { title: '发票状态', index: 'sts', render: 'sts', className: 'text-center', width: '120px' },
      { title: '上传日期', index: 'uoloadDate', className: 'text-center', width: '180px' }
    ];
  }

  /**
   *撤回
   * @param record 记录实例
   */
  recall() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要撤回的数据');
      return;
    }
    let ids: any[] = [];
    this.selectedRows.forEach(item => {
      ids.push(item.id);
    });

    this.modal.confirm({
      nzTitle: '撤回提示',
      nzContent: ' 撤回后可以重新上传，重新上传会覆盖已上传数据，确定要撤回？',
      nzOkText: '确定',
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_invoiceUpload_withdraw, { ids }).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');
            this.search();
          }
        });
      }
    });
  }

  /**
   *撤销
   * @param record 记录实例
   */
  unnormal(value: any) {
    // if (this.selectedRows.length === 0) {
    //   this.openWainingModal('请选择需要更新的数据！');
    //   return;
    // }
    console.log(this.selectedRows);
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    this.modal.confirm({
      nzTitle: '税务审核结果',
      nzContent: `${value?.exceptionInfo}`,
      nzOkText: '确定',
      nzCancelText: '',
      nzOnOk: () => {
        this.service.request(this.service.$api_get_recessionTaxOrder, params).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');
            this.search();
          }
        });
      }
    });
  }

  selectChange(item: any) {
    this.selectedIndex = item?.value || '';

    setTimeout(() => {
      this.st.load();
    });
  }

  /**
   * 上传
   */
  upload() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要上传的数据');
      return;
    }
    let params: any[] = [];
    this.selectedRows.forEach(item => {
      params.push(item.id);
    });
    this.service.request(this.service.$api_uploadInvoice, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('上传成功');
        this.st.load();
      }
    });
  }

  /**
   * 查看监管审核结果
   */
  viewAuditResult(record: any) {
    if (record?.billStatus !== '2') {
      return;
    }
    this.openWainingModal('监管审核结果', record?.result);
  }

  search() {
    this.st.load(1);
  }

  /**
   * 异步导出
   */
  export() {
    this.service.exportStart({...this.reqParams, pageSize: -1  }, this.service.$api_invoiceUpload_export);
  }

  openWainingModal(content: string, title = '提示') {
    this.modal.warning({
      nzMask: false,
      nzTitle: title,
      nzContent: content
    });
  }
}
